<template>
  <div style="position:absolute; z-index: 999;width:100%">
    <input type="file" @change="handleFileChange" />
    <div :style="{ transform: `scale(${0.4})`, top:'0px', left:'400px', position:'absolute' }">
        <StateButton class="stateButton3-2" imgSrc="./assets/ui/翻页按钮-左.png" @click="onLeftClick"></StateButton>
        <StateButton class="stateButton3-2" imgSrc="./assets/ui/翻页按钮-右.png" style="left: 200px;" @click="onRightClick"></StateButton>
        <StateButton class="stateButton3-3" imgSrc="./assets/ui/小按钮-导出.png" style="left: 400px;" @click="printContent"></StateButton>
    </div>
    <el-input type="number" v-model="input" style="left:450px;width: 90px" placeholder="Please input" @input="onInput">东方</el-input>
    <div style="position: absolute;left: 810px;top: 10px;">
      <el-button v-for="(item, index) in borderList" @click="onTableClick($event, index)">{{ item.title }}</el-button>
    </div>
  </div>
  
  <!--<div v-for="item in sql">-->
  <el-scrollbar style="position: absolute;top: 80px;border: 1px solid red; width: 97%;height: 90%;">
    <div id="mypdf" v-for="(item1, index1) in curWord">
        <!--<el-text>{{ item1.key }}</el-text>
        <el-text></el-text>-->
        <div v-html="item1.value"></div>
    </div>
  </el-scrollbar>
  <!--</div>-->
</template>

<script setup lang="ts">

import { ref } from 'vue';
import { ElMessage } from 'element-plus'
import HelloWorld from './components/HelloWorld.vue';
import StateButton from './components/StateButton.vue';
// 引入jsPDF库
import jsPDF from 'jspdf';
// 引入Print.js库
import PrintJS from 'print-js';
// 引入html2canvas和jsPDF库
import html2canvas from 'html2canvas';

// // 创建一个新的PDF文档
// const doc = new jsPDF();
 
// // 添加文本到PDF文档
// doc.text('<div>Hello world!</div>', 10, 10);
 
// // 保存PDF（默认下载）
// doc.save('hello_world.pdf');
const input = ref(0);
let values:any[] = [];
const sql = ref(values);
const curWord = ref([{key:'',value:''}]);
let page:number = 0;

const borderList = ref([{border:'<table border="1" ', title:'当前显示'}]);

function initTableValue(){
  let info:any = curWord.value[0];
  let str:string = info.value;
  let index2:number = 0;
  let start:number = 0;
  let list:any = borderList.value;
  list.length = 0;
  while(index2 != -1){
    index2 = str.indexOf("<table", start);
    if(index2 != -1){
      list.push({border:'<table border="1" ', title:'当前显示'});
      start = index2 + 15;
    }
  }
  refreshTable();
}
function refreshTable(){
  let info:any = curWord.value[0];
  let str:string = info.value;
  let index2:number = 0;
  let start:number = 0;
  let list:any = borderList.value;
  let count:number = 0;
  const b0:string = '<table border="0" ';
  const b1:string = '<table border="1" ';

  if(list.length <= 0){
    return;
  }
  while(index2 != -1){
    index2 = str.indexOf("<table", start);

    if(index2 != -1){
      if(list[count].border == b0){
        // if(str.indexOf(b0, index2) == -1){
          var str1 = str.substring(0, index2);
          var str2 = str.substring(index2, index2+b0.length);
          var str3 = str.substring(index2+b0.length, str.length);

          // let regex = /<table/g;
          // str2 = str2.replace(regex, b0);
          str2 = b0;
          str = str1 + str2 + str3;
          count ++;
        // }
        start = index2 + b0.length;
      }
      else{
        // if(str.indexOf(b1, index2) == -1){
          var str1 = str.substring(0, index2);
          var str2 = str.substring(index2, index2+b1.length);
          var str3 = str.substring(index2+b1.length, str.length);

          // let regex = /<table/g;
          // str2 = str2.replace(regex, b1);
          str2 = b1;
          str = str1 + str2 + str3;
          count ++;
        // }
        start = index2 + b1.length;
      }
    }
    
  }
  info.value = str;
  curWord.value[0] = info;
}
function onTableClick(e:any, index:number){
  
  let list:any = borderList.value;
  
  const b0:string = '<table border="0" ';
  const b1:string = '<table border="1" ';

  var borderstr = list[index].border;
  if(borderstr == b0){
    list[index].border = b1;
    list[index].title = '当前显示';
  }
  else{
    list[index].border = b0;
    list[index].title = '当前隐藏';
  }
  refreshTable();

  // let regex = /<table/g; // g标志表示全局匹配
  // if(valueArr[j].indexOf("<table") != -1){
  //       valueArr[j] = valueArr[j].replace(regex, '<table border="1" ');
  //   }
}
function onInput(){
  page = input.value;
  if(page < 0) page = 0;
  if(page >= sql.value.length){
      ElMessage('已到达最后一页！');
      page = sql.value.length - 1;
    }
    else{
      ElMessage({offset:70,message:'当前第' + (page+1) + "页！",type: 'success'});
    }

  curWord.value = sql.value[page];
}
function onLeftClick(){
    page --;
    if(page < 0) page = 0;
    input.value = page;
    ElMessage({offset:70,message:'当前第' + (page+1) + "页！",type: 'success'});
    
    curWord.value = sql.value[page];
    initTableValue();
}

function printContent() {
      let printFrame = (document.getElementById('mypdf') as any).cloneNode(true);
      let printFrameWindow:any = window.open('qqq', '_blank');
      printFrameWindow.document.open();
      var str = '<html><head><meta charset="UTF-8"><title>'+(page+1)+'/'+sql.value.length+'</title></head><body>';
      str += '<style type="text/css" media="print">@media @page { margin: 0; } body { margin: 1cm; }</style>';
      printFrameWindow.document.write(str);
      printFrameWindow.document.write(printFrame.innerHTML);
      printFrameWindow.document.write('</body></html>');
      printFrameWindow.document.close();
      printFrameWindow.focus();
 
      // 调用window.print进行打印
      printFrameWindow.print({mediaType:'print',pageSize:'A3',orientation:'landscape'});
    }
function onPrintClick(){
  let newstr:any = (document.getElementById('mypdf') as any).innerHTML;
    let oldstr:any = document.body.innerHTML;
    document.body.innerHTML = newstr;
    window.print();
    document.body.innerHTML = oldstr;
}
function onRightClick(){
    page ++;
    if(page >= sql.value.length){
      ElMessage('已到达最后一页！');
      page = sql.value.length - 1;
    }
    else{
      ElMessage({offset:70,message:'当前第' + (page+1) + "页！",type: 'success'});
    }
    input.value = page;
    curWord.value = sql.value[page];
    initTableValue();

    
    // 假设你想导出这个元素
    // let element:any = document.getElementById('mypdf');
    
    // const doc = new jsPDF();
    // doc.fromHTML(document.documentElement, 15, 15, {
    //             'width': 170
    //         });
    //         doc.save('hello_world.pdf');
    // // 使用html2canvas将元素转换为画布
    // html2canvas(element).then(canvas => {
    //     // 创建一个新的PDF文档并添加画布
    //     const pdf = new jsPDF();
    //     pdf.addImage(canvas, 'JPEG', 0, 0, element.scrollWidth, element.scrollHeight);
      
    //     // 保存PDF（默认下载）
    //     pdf.save('element.pdf');
    // });
    // // 使用Print.js导出PDF
    // PrintJS({
    //   printable: '#mypdf', // 要导出的元素的ID
    //   type: 'pdf',
    //   documentTitle: 'pdftest' // PDF文档标题
    // });
}
function handleFileChange(event:any) {
      const file = event.target.files[0];
      const fileReader = new FileReader();
      fileReader.onload = () => {

        values = sql.value;

        let content:any = fileReader.result;
        // console.log(content);
        // 处理文件内容
        // ...
        var arr1 = content.split("INSERT INTO `hzyy_instruction_data` (");
        let str:string;
        arr1.shift();
        for(var i=0; i<arr1.length; i++){
            str = arr1[i];
            if(!str){
              continue;
            }
            var attrs = str.substring(0, str.indexOf(") VALUES ("));
            var attrArr = attrs.split(", ");
            
            var value = str.substring(str.indexOf("VALUES (")+8, str.length -3);
            var valueArr = value.split(", '");
            values[i] = [];

            //table记录


            for(var j=0; j<attrArr.length; j++){
                if(valueArr[j] && j == valueArr.length-1){
                    valueArr[j] = valueArr[j].replace("'","");
                    let regex = /<table/g; // g标志表示全局匹配
                    if(valueArr[j].indexOf("<table") != -1){
                          valueArr[j] = valueArr[j].replace(regex, '<table border="1" ');
                      }
                    values[i].push({key:attrArr[j], value:valueArr[j]});
                    if(valueArr[j].indexOf("阿莫西林") != -1){
                        page = i;
                    }
                }
                
            }
            // sql.value = values;
            curWord.value = sql.value[page];
        }
        
        initTableValue();
        console.log("加载完成！");
        ElMessage({offset:70,message:'加载完成！',type: 'success'});
      };
      fileReader.readAsText(file);
    }

</script>


<style scoped>


.logo {
  display: block;
  margin: 0 auto 2rem;
}
.stateButton3-3{
  position:absolute;
  width: 304px;
  height:114.33px;
  top: 8px;
}
.stateButton3-2{
  position:absolute;
  width: 109px;
  height:119px;
  top: 8px;
}


</style>
